package com.labor_management_system.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.labor_management_system.Entity.Employee;
import com.labor_management_system.Entity.Payroll;
import com.labor_management_system.Service.EmployeeService;
import com.labor_management_system.Service.PayrollService;
import com.labor_management_system.Service.TeamService;
import com.labor_management_system.Utils.R;
import com.labor_management_system.Vo.PayrollVo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
@CrossOrigin
@RestController
public class PayrollRecordsController {
    //工资记录管理
    @Autowired
    private PayrollService payrollService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private EmployeeService employeeService;

    /**
     * 查询工资记录分页
     * @return
     */
    @PostMapping("/TEST/Gen4")
    public R Gen3(@RequestParam(value = "count") int count){
        for (int i = 0; i < count; i++) {
            Payroll payroll = generateRandomPayroll();
            payrollService.getBaseMapper().insert(payroll); // 调用 mybatis-plus 的插入方法插入数据
        }
        return R.ok();
    }
    private Payroll generateRandomPayroll() {
        Payroll payroll = new Payroll();
        payroll.setId(UUID.randomUUID().toString()); // 生成随机的 id
        payroll.setEid(generateRandomEid()); // 生成随机的工人id
        payroll.setAttendanceDaysCmonth(generateRandomAttendanceDays()); // 生成随机的出勤天数
        payroll.setWages(generateRandomWages()); // 生成随机的工资
        payroll.setDates(generateRandomTimestamp()); // 生成随机的时间戳作为日期
        payroll.setAccumulatedPayableWages(generateRandomAccumulatedPayableWages()); // 生成随机的累计应付工资
        payroll.setAccumulatedPaidWages(generateRandomAccumulatedPaidWages()); // 生成随机的累计已付工资
        payroll.setAccumulatedUnpaidWages(generateRandomAccumulatedUnpaidWages()); // 生成随机的累计欠付工资

        return payroll;
    }
    // 以下是示例的随机数生成函数，你需要根据实际需求编写这些函数
    private String generateRandomEid() {
        // 生成随机的工人id的逻辑
        List<Employee> employees = employeeService.getBaseMapper().selectList(null); // 获取所有员工信息
        int randomIndex = new Random().nextInt(employees.size()); // 生成一个随机索引
        return employees.get(randomIndex).getEmployeeId(); // 返回随机选择的员工的 eid
    }

    private Integer generateRandomAttendanceDays() {
        // 生成随机的出勤天数的逻辑
        return 20 + (int)(Math.random() * 10); // 生成 20 到 30 的随机数
    }

    private Integer generateRandomWages() {
        // 生成随机的工资的逻辑
        return 2000 + (int)(Math.random() * 1000); // 生成 2000 到 3000 的随机数
    }

    private Long generateRandomTimestamp() {
        long offset = Timestamp.valueOf("2020-01-01 00:00:00").getTime(); // 开始时间戳
        long end = Timestamp.valueOf("2025-12-31 23:59:59").getTime(); // 结束时间戳
        long diff = end - offset + 1;
        return offset + (long) (Math.random() * diff);
    }

    private Double generateRandomAccumulatedPayableWages() {
        // 生成随机的累计应付工资的逻辑
        return 10000 + Math.random() * 5000; // 生成 10000 到 15000 的随机数
    }

    private Double generateRandomAccumulatedPaidWages() {
        // 生成随机的累计已付工资的逻辑
        return 8000 + Math.random() * 4000; // 生成 8000 到 12000 的随机数
    }

    private Double generateRandomAccumulatedUnpaidWages() {
        // 生成随机的累计欠付工资的逻辑
        return 2000 + Math.random() * 2000; // 生成 2000 到 4000 的随机数
    }

    //TODO:
    @PostMapping("/GET/page")
    public R page(Page page, PayrollVo payrollVo){
        LambdaQueryWrapper<Payroll> queryWrapper = new LambdaQueryWrapper<>();
        //通过名字拿取id
        //
        queryWrapper.inSql(payrollVo.getEname()!=null&&payrollVo.getEname().length()>0,
                Payroll::getEid,"select employee_id from employee where employee_name = '"+payrollVo.getEname()+"'");
        queryWrapper.inSql(payrollVo.getTname()!=null&&payrollVo.getTname().length()>0,
                Payroll::getEid,"select employee_id from employee where team_id in(select team_id from team where team_name = '"+payrollVo.getTname()+"')");
        queryWrapper.eq(payrollVo.getAttendanceDate()!=null,
                Payroll::getDates,payrollVo.getAttendanceDate());
        IPage<Payroll> iPage = payrollService.page(page,queryWrapper);

        for(Payroll payroll : iPage.getRecords()){
            payroll.setEmployee(employeeService.getBaseMapper().selectById(payroll.getEid()));
            System.out.println(payroll.getEmployee().getEmployeeName()+"\n");
            if(payroll.getEmployee()!=null){
                payroll.setTname(teamService.getById(payroll.getEmployee().getTeamId()).getTeamName());
            }
        }
        return R.ok().data("info",iPage);
    }


    /**
     * 导出转excel
     * 将文件以数据流格式输出
     * @return
     */
//    http://localhost:8088/payroll/export
    @RequestMapping("/export")
    public void export(Page page, PayrollVo payrollVo) throws IOException {
        R promotionWord=page(page, payrollVo);
        Map<String, Object> promotionWordData =promotionWord.getData();
//        R result = (R) promotionWord.getData();
//        JSONObject jsonObject = new JSONObject();
////        jsonObject.put("success", result.getSuccess());
////        jsonObject.put("code", result.getCode());
////        jsonObject.put("message", result.getMessage());
//        jsonObject.put("data", new JSONObject(result.getData()));
        try {
            // 导出JSON数据到Excel文件
            exportJsonToExcel(promotionWordData, "D:\\360MoveData\\Users\\HP\\Desktop\\output.xlsx");
            System.out.println("JSON数据已成功导出到Excel文件");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 将JSON数据导出到Excel文件
    public static void exportJsonToExcel(Map<String, Object> jsonObject, String filePath) throws Exception {

        // 创建一个新的Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");


        // 创建表头
        Row headerRow = sheet.createRow(0);
        int columnIndex = 0;//表头标记

//            HSSFRow rowTtile = (HSSFRow) sheet.createRow(1000);

        // 遍历第一个JSON对象的键，作为Excel表头
        for (String key : jsonObject.keySet()) {
            Cell cell = headerRow.createCell(columnIndex++);//在columnIndex行创建一个新的单元格（Cell），并赋值
            cell.setCellValue(key);//将 JSON 数据中的键作为 Excel 表格的表头
        }

        // 填充数据
        int rowIndex = 1;

        Row dataRow =sheet.createRow(rowIndex++);
        columnIndex = 0;

        // 将JSON数据填充到Excel中
        for (String key : jsonObject.keySet()) {
            Cell cell = dataRow.createCell(columnIndex++);//在columnIndex行创建一个新的单元格（Cell），并赋值
            cell.setCellValue(jsonObject.get(key).toString());
        }

        // 保存Excel文件
        FileOutputStream fileOut = new FileOutputStream(filePath);
        workbook.write(fileOut);
        fileOut.close();

        workbook.close();
    }
}
